package com.efounder.agency.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SearchView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.chat.adapter.SearchTaskListAdapter;
import com.efounder.chat.model.Task;
import com.efounder.ospmobilelib.R;
import com.efounder.util.SetFMTEnvironmetVariableValueUtil;
import com.pansoft.espcomp.sortlistview.HanyuParser;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Deprecated
/**
 * 已废弃 新的任务搜索 com.efounder.taskcomps.TaskSearchActivityNew
 */
public class TaskSearchActivity extends AbActivity {

    private ArrayList<Task> taskDataList;
    private RecyclerView mLv;
    private SearchView mSearchView;
    private SearchView.SearchAutoComplete mSearchAutoComplete;
    private SearchTaskListAdapter adapter;
    private ArrayList<Task> searchResultList;
    private HanyuParser hanyuParser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_search);
        Intent intent = getIntent();
        taskDataList = intent.getParcelableArrayListExtra("taskDataList");
        searchResultList = new ArrayList<>();
        hanyuParser = new HanyuParser();
        initFindView();
        searchViewConfig();
    }

    private void searchViewConfig() {
        mSearchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);
        mSearchView.setQueryHint("请输入任务关键信息");
//        mSearchView.setSubmitButtonEnabled(false);
        //设置输入框提示文字样式
        mSearchAutoComplete.setHintTextColor(getResources().getColor(android.R.color.darker_gray));
        mSearchAutoComplete.setTextColor(getResources().getColor(android.R.color.background_dark));
        mSearchAutoComplete.setTextSize(14);
        //设置触发查询的最少字符数（默认2个字符才会触发查询）
        mSearchAutoComplete.setThreshold(1);

        //设置搜索框有字时显示叉叉，无字时隐藏叉叉
        mSearchView.onActionViewExpanded();
        mSearchView.setIconified(false);
        mSearchView.setIconifiedByDefault(false);
        /**
         * 去掉searchview 下划线
         */
        try {
            Class<?> argClass = mSearchView.getClass();
            //--指定某个私有属性,mSearchPlate是搜索框父布局的名字
            Field ownField = argClass.getDeclaredField("mSearchPlate");
            //--暴力反射,只有暴力反射才能拿到私有属性
            ownField.setAccessible(true);
            View mView = (View) ownField.get(mSearchView);
            //--设置背景
            mView.setBackgroundResource(R.drawable.shape_search_view);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * searchView 放大镜 叉号 替换图片
         */
        ImageView closeButton = (ImageView) mSearchView.findViewById(R.id.search_close_btn);
        ImageView searchButton = (ImageView) mSearchView.findViewById(R.id.search_button);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
//        int width = wm.getDefaultDisplay().getWidth();
//        searchButton.setPadding(DensityUtil.dip2px(this, 10), 0, width * 2 / 3, 0);
        Drawable topList = getResources().getDrawable(R.mipmap.delete);
        Drawable drawable = tintDrawable(topList, Color.parseColor("#999999"));
        closeButton.setImageDrawable(drawable);
        //修改搜索框控件间的间隔（这样只是为了更加接近网易云音乐的搜索框）
        LinearLayout search_edit_frame = (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) search_edit_frame.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        search_edit_frame.setLayoutParams(params);

        //监听SearchView的内容
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                ArrayList<Task> resultList = TextUtils.isEmpty(s) ? null : queryData(s);
                setAdapter(resultList);
                return false;
            }
        });
    }

    private ArrayList<Task> queryData(String key) {
        if (searchResultList != null) {
            searchResultList.clear();
        } else {
            searchResultList = new ArrayList<>();
        }

        for (int i = 0; i < taskDataList.size(); i++) {
            Task task = taskDataList.get(i);
            String title = task.getTitle();
            if (title.contains(key)) {
                searchResultList.add(task);
            } else {
                String keyPinyin = "";
                String characterPinYin = "";

                for (int j = 0; j < key.length(); j++) {

                    keyPinyin += (key.charAt(j) + "").toUpperCase(Locale.getDefault());
                }
                for (int j = 0; j < title.length(); j++) {
                    char c = title.charAt(j);
                    String keyWord = hanyuParser.getCharacterPinYin(c);
                    if (null != keyWord)
                        characterPinYin += keyWord.substring(0, 1).toUpperCase(Locale.getDefault());
                }
                if (characterPinYin.contains(keyPinyin))
                    searchResultList.add(task);
            }

        }
        return searchResultList;
    }

    private void setAdapter(ArrayList<Task> searchResultList) {
        if (mLv.getAdapter() == null) {
            mLv.setLayoutManager(new LinearLayoutManager(this));
            adapter = new SearchTaskListAdapter(this, searchResultList);
            setItemClickListener(searchResultList);
            mLv.setAdapter(adapter);
        } else {
            ArrayList<Task> tasks = new ArrayList<>();
            if (searchResultList != null)
                tasks.addAll(searchResultList);
            adapter.updateSearchResult(tasks);
        }
    }

    private void setItemClickListener(final ArrayList<Task> mData) {
        adapter.setOnItemClickLitener(new SearchTaskListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("TaskDetail_FLOW_ID", null);
                map.put("task_flowId", mData.get(position).getFlow_id());
                map.put("task_header", mData.get(position).getTitle());
                map.put("task_avatar", "");
                map.put("task_badgeValue", String.valueOf(mData.get(position).getTodoNum()));

                Map<String, Object> fmtMap = SetFMTEnvironmetVariableValueUtil.setFmtEnvironmentValue(TaskSearchActivity.this, mData.get(position).getFlow_id());
                map.putAll(fmtMap);
                try {
                    if (map.get("hfmt") == null) {
                        Toast.makeText(TaskSearchActivity.this, "此条在Mobile_FMT中未配置，请联系管理员", Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    Intent intent = new Intent(TaskSearchActivity.this, Class.forName("com.efounder.RNTaskActivity"));
                    Intent intent = new Intent(TaskSearchActivity.this, Class.forName("com.efounder.taskcomps.activity.TaskListActivity"));
                    intent.putExtra("status", mData.get(position).getStatus());
                    intent.putExtra("args", (Serializable) map);
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    private Drawable tintDrawable(Drawable drawable, int color) {
        Drawable mutate = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTint(mutate, color);
        return mutate;
    }

    private void initFindView() {
        mSearchView = (SearchView) findViewById(R.id.search_view);
        mLv = (RecyclerView) findViewById(R.id.lv);
        View cancelButton = findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}
